import request from '@/utils/request';
import { PlanItemParam, TableListItem } from './data.d';
import qs from 'qs';

const getRandomuserParams = (params: any) => {
  return {
    pageSize: params.pageSize,
    pageNo: params.current,
    ...params,
  };
};

const dateFormat = (fmt:string, date:Date) => {
  let ret;
  const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "m+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "H+": date.getHours().toString(),           // 时
      "M+": date.getMinutes().toString(),         // 分
      "S+": date.getSeconds().toString()          // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
  };
  return fmt;
}

//计划列表
export async function planList(params: TableListItem) {
  params = getRandomuserParams(params);
  return request('/api/plan/list/pageList', {
    method: 'GET',
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    params,
  }).then((response) => {
    if (response && response.code === 200) {
      //数据转换
      const obj = new Object();
      let list = response.data.list;
      for (var i in list) {
        list[i].index = parseInt(i)+1;//序号
        list[i].key = list[i].id;

        if(list[i].publishStatus === 0){//发布状态
          list[i].publishStatusText = 0;
        }else if(list[i].publishStatus === 1){
          list[i].publishStatusText = `发布中（${list[i].successDeviceCount}/${list[i].totalDeviceCount}）`;
        }else if(list[i].publishStatus === 2){
          list[i].publishStatusText = 2;
        }else if(list[i].publishStatus === 4){
          list[i].publishStatusText = 4;
        }


        if(list[i].startDatetime && list[i].endDatetime){ //播放日期
          const startDatetime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(list[i].startDatetime));
          const endDatetime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(list[i].endDatetime));
          list[i].startDatetime = startDatetime;
          list[i].endDatetime = endDatetime;
          list[i].playDatetime = dateFormat("YYYY-mm-dd", new Date(list[i].startDatetime)) + ' ~ ' + dateFormat("YYYY-mm-dd", new Date(list[i].endDatetime));
        }else{
          list[i].playDatetime = "一直播放";
        }
        if(list[i].publishDatetime != null){
          list[i].createDatetime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(list[i].createDatetime));//创建时间
          list[i].publishDatetime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date(list[i].publishDatetime));
        }
      }
      obj['data'] = list;
      obj['pageCount'] = response.data.pageCount;
      obj['current'] = response.data.pageNo;
      obj['total'] = response.data.totalCount;
      return obj;
    }
  });
}
//计划审核列表
export async function planAuditList(params: TableListItem) {
  params = getRandomuserParams(params);
  return request('/api/plan/audit/pageList', {
    method: 'GET',
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    params,
  }).then((response) => {
    if (response && response.code === 200) {
      //数据转换
      const obj = new Object();
      let list = response.data.list;
      for (var i in list) {
        list[i].index = parseInt(i)+1;//序号
        list[i].key = list[i].id;
        if(list[i].startDatetime && list[i].endDatetime){ //播放日期
          list[i].playDatetime = dateFormat("YYYY-mm-dd", new Date(list[i].startDatetime)) + ' ~ ' + dateFormat("YYYY-mm-dd", new Date(list[i].endDatetime));
        }else{
          list[i].playDatetime = "一直播放";
        }
      }
      obj['data'] = list;
      obj['pageCount'] = response.data.pageCount;
      obj['current'] = response.data.pageNo;
      obj['total'] = response.data.totalCount;
      return obj;
    }
  });
}
//分配标签
export async function setTag(params: any) {
  return request('/api/plan/list/setTags', {
    method: 'PUT',
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    data:{
      ...params,
      method: 'update',
    }
  });
}
//计划复制
export async function planCopy(id: number) {
  return request(`/api/plan/list/copyPlan/${id}`, {
    method: 'POST',
    timeout:180000,
    headers: {
      Authorization: localStorage.getItem('token'),
    },
  });
}

//下载请求
export async function downloadZip(id: number) {
  return request(`/api/plan/list/downloadZip/${id}`, {
    method: 'GET',
    timeout:180000,
    headers: {
      Authorization: localStorage.getItem('token'),
    },
  });
}

//计划重新打包
export async function repackPlan(id: any) {
  return request(`/api/plan/list/repackPlan/${id}`, {
    method: 'PUT',
    timeout:180000,
    headers: {
      Authorization: localStorage.getItem('token'),
    },
  });
}
//计划添加
export async function planAdd(params: PlanItemParam) {
  return request('/api/plan/list/add', {
    method: 'POST',
    timeout:180000,
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    data: {
      ...params,
      // method: 'update',
    },
  });
}
//计划编辑
export async function planUpdate(id:number, param: PlanItemParam) {
  return request(`/api/plan/list/updatePlan/${id}`, {
    method: 'PUT',
    timeout:180000,
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    data: {
      ...param,
    },
  });
}
//计划删除
export async function planRemove(params: any) {
  return request('/api/plan/list/delete', {
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    method: 'delete',
    params,
  });
}
//批量删除计划
export async function batchDelete(params: any) {
  return request('/api/plan/list/batchDelete/', {
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    method: 'delete',
    params,
  });
}
//计划通过
export async function planPass(code: string,param:any) {
  return request(`/api/plan/audit/pass/${(code)}`, {
    method: 'PUT',
    headers: {
      Authorization: localStorage.getItem('token'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: qs.stringify(param, { arrayFormat: 'indices', allowDots: true }),
  });
}
//计划驳回
export async function planReject(code: string,param:any) {
  return request(`/api/plan/audit/reject/${(code)}`, {
    method: 'PUT',
    headers: {
      Authorization: localStorage.getItem('token'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: qs.stringify(param, { arrayFormat: 'indices', allowDots: true }),
  });
}
//计划详情列表
export async function planDetail(code: string) {
  return request(`/api/plan/list/detail/${(code)}`, {
    method: 'GET',
    headers: {
      Authorization: localStorage.getItem('token'),
    },
  }).then((response) => {
    if (response && response.code === 200) {
      const obj = new Object();
      let list = response.data.deviceList;
      for (var i in list) {
        list[i].index = parseInt(i)+1;//序号
        list[i].key = list[i].id;
        list[i].resolution = list[i].width+'x'+list[i].height;
      }
      obj['data'] = list;
      return obj;
    }
  });
}

//计划审核列表
export async function planReviewList(params: TableListItem) {
  params = getRandomuserParams(params);
  return request('/api/plan/list/pageList', {
    method: 'GET',
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    params,
  }).then((response) => {
    if (response && response.code === 200) {
      //数据转换
      const obj = new Object();
      let list = response.data.list;
      for (var i in list) {
        list[i].key = list[i].id;
      }
      obj['data'] = list;
      obj['pageCount'] = response.data.pageCount;
      obj['current'] = response.data.pageNo;
      obj['total'] = response.data.totalCount;
      return obj;
    }
  });
}
